from django.http import HttpResponse
from django.utils.deprecation import MiddlewareMixin
from rest_framework import status


import logging

# import traceback

logger = logging.getLogger("sys_error")


class SessionMiddleware(MiddlewareMixin):
    """自定义请求中间件"""

    def process_request(self, request):
        """请求时处理函数"""
        # print("###收到请求...", request.method, request.path)
        # if request.path.find("/api/EditToken/") > -1:
        #     if request.method == "PATCH":
        #         print(dir(request))
        #         print(request.META)
        return None

    def process_view(self, request, view_func, view_args, view_kwargs):
        """视图处理函数"""
        # traceback.print_exc()
        # print("###载入视图...", request.method, request.path)

        return None

    def process_exception(self, request, exception):
        """发生错误时处理函数"""
        # print("###系统错误...", request.method, request.path)
        # print("###错误消息...", exception)
        logger.error(f"{request.method} {request.path} {exception}")
        return HttpResponse('{"rescode": 555, "resmsg": "内部错误"}')

    def process_response(self, request, response):
        """直接返回处理函数"""
        # print("###直接返回...", request.method, request.path, response.status_code)
        response["Access-Control-Allow-Origin"] = "*"
        response["Access-Control-Allow-Headers"] = "Content-Type"
        response[
            "Access-Control-Allow-Methods"
        ] = "GET, POST, PUT, PATCH, DELETE, OPTIONS"
        return response

    def process_template_response(self, request, response):
        """模板返回处理函数"""
        # print("###模板返回...", request.method, request.path, response.status_code)
        # print(response.data)
        # 处理反序列化字段唯一错误
        if not response.status_code == 200:
            response.data = {"rescode": response.status_code, "resmsg": response.data}

        response.status = status.HTTP_200_OK
        response.status_code = 200
        return response
